package com.spzx.cart.service.impl;

import com.spzx.cart.domain.CartItem;
import com.spzx.cart.service.CartService;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.ProductSku;
import jakarta.annotation.Resource;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class CartServiceImpl implements CartService {


    @Autowired
    RedisTemplate redisTemplate;

    @Resource
    RemoteProductService remoteProductService;


    @Override
    public boolean addToCart(Long skuId, Integer num) {
        CartItem cartItem= new CartItem();

        //获取当前用户的购物车
        BoundHashOperations<String, String, CartItem> cart = getCart();

        Boolean hasKey = cart.hasKey(skuId.toString());

        //判断当前购物车是否已存在skuID的购物项 购物项数量+num
        if (hasKey){
            //获取购物项
             cartItem = cart.get(skuId.toString());

             //修改购物项的数量
             cartItem.setSkuNum(cartItem.getSkuNum()+num);
             cartItem.setUpdateTime(new Date());



        }else {
            //如果当前用户的购物车中不存在skuId的购物项，新建购物项存入，购物项数量为num
            // 查询购物项 需要sku详情

            //根据skuId 查询sku详情 通过远程调用
            R<ProductSku> productSkuR = remoteProductService.getSkuById(skuId);
            if (productSkuR.getCode()!=200){
                throw new ServiceException("addToCart方法中远程调用失败"+productSkuR.getMsg());
            }

            ProductSku productSku= productSkuR.getData();

            cartItem.setCreateTime(new Date());
            cartItem.setUpdateTime(new Date());
            cartItem.setUserId(SecurityUtils.getUserId());
            cartItem.setSkuId(skuId);
            cartItem.setSkuNum(num);
            cartItem.setCartPrice(productSku.getSalePrice());
            cartItem.setSkuPrice(productSku.getSalePrice());
            cartItem.setThumbImg(productSku.getThumbImg());
            cartItem.setSkuName(productSku.getSkuName());
        }
        //将数据存储到redis中
        //将更新后的数据设置到redis中

        //redisTemplate给我们 封装的方法
        cart.put(skuId.toString(),cartItem);


        return true;
    }

    @Override
    public boolean checkCart(Long skuId, Integer checkStatus) {

        //1 获取购物车
        BoundHashOperations<String, String, CartItem> cart = getCart();


        //2 获取购物项
        CartItem cartItem = cart.get(skuId.toString());
        if (cartItem==null){
            throw new ServiceException("购物车商品为空异常，请刷新页面");
        }

        //3 修改选中状态同步到redis中
        cartItem.setIsChecked(checkStatus);
        cartItem.setUpdateTime(new Date());
        cart.put(skuId.toString(),cartItem);
        return true;
    }

    @Override
    public List<CartItem> selectCartList() {
        BoundHashOperations<String, String, CartItem> cart = getCart();
        return cart.values();
    }

    @Override
    public boolean deletedCartByskuId(Long skuId) {
        BoundHashOperations<String, String, CartItem> cart = getCart();

        Long del = cart.delete(skuId);
        return del!= 0;
    }

    @Override
    public boolean clearCart() {
        BoundHashOperations<String, String, CartItem> cart = getCart();
        Boolean flag = redisTemplate.delete("spzx:cart:" + SecurityUtils.getUserId());
        return flag;
    }

    @Override
    public boolean allCheckCart(Integer checkStatus) {
        BoundHashOperations<String, String, CartItem> cart = getCart();

        Map<String, CartItem> entries = cart.entries();
        //获取所有购物车中的条目 遍历 修改状态 更新到redis
        entries.forEach((skuIdStr,cartItem)->{
            cartItem.setIsChecked(checkStatus);
            cart.put(skuIdStr,cartItem);
        });


        return true;
    }

    @Override
    public List<CartItem> selectCheckedCartItems(Long userId) {

        BoundHashOperations<String, String, CartItem> cart = getCart();
        return cart.values().stream().filter(cartItem -> cartItem.getIsChecked()==1).collect(Collectors.toList());
    }


    //用来获取当前用户在redis中有哪些写购物信息
    private BoundHashOperations<String,String, CartItem> getCart(){
        //hash结构存储用户购物车以及购物车中的多个购物项数据
        //根据key获取redis中的Hash结构   泛型1：key的类型，泛型2，hash的键的类型，泛型3hash值的类型
        return redisTemplate.boundHashOps("spzx:cart:" + SecurityUtils.getUserId());
    }


    //删除选中购物项
    public void delCheckedCartItems(Long userId){
        //获取用户的购物车
        BoundHashOperations<String, String, CartItem> cart = redisTemplate
                .boundHashOps("spzx:cart:" + userId);
        List<String> skuIds = cart.values().stream().filter(cartItem -> cartItem.getIsChecked() == 1)
                .map(cartItem -> String.valueOf(cartItem.getSkuId())).collect(Collectors.toList());
        // skuId-> cartItem
        cart.delete(skuIds.toArray());
    }
}
